package cn.bonoon.core;

import java.util.Calendar;

/**
 * 周期的类型，应该是通用的，所有周期策略、周期任务等都适用
 * @author jackson
 *
 */
public enum PeriodType {
	
	/** 每天 */
	DAILY{
		@Override
		public Calendar resolve(int expression, int duration) {
			int minute = expression % 100;
			int hour = expression / 100;
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.HOUR_OF_DAY, hour);
			cal.set(Calendar.MINUTE, minute);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
//			if(cal.getTimeInMillis() < System.currentTimeMillis()){
//				cal.add(Calendar.DAY_OF_MONTH, 1);
//			}
//			return cal;
			return check(cal, Calendar.DAY_OF_MONTH, duration);//应该是第二天了
		}
	},

	/** 每周 */
	WEEKLY{
		@Override
		public Calendar resolve(int expression, int duration) {
			int minute = expression % 100;
			expression = expression / 100;
			int hour = expression % 100;
			int dayofw = expression / 100;
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.WEDNESDAY, dayofw);
			cal.set(Calendar.HOUR_OF_DAY, hour);
			cal.set(Calendar.MINUTE, minute);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
//			if(cal.getTimeInMillis() < System.currentTimeMillis()){
//				//去到下个星期了
//				cal.add(Calendar.WEEK_OF_YEAR, 1);
//			}
//			return cal;
			return check(cal, Calendar.WEEK_OF_YEAR, duration);//下一个星期
		}
	},

	/** 每月 */
	MONTHLY{
		@Override
		public Calendar resolve(int expression, int duration) {
			int minute = expression % 100;
			expression = expression / 100;
			int hour = expression % 100;
			int dayofm = expression / 100;
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.DAY_OF_MONTH, dayofm);
			cal.set(Calendar.HOUR_OF_DAY, hour);
			cal.set(Calendar.MINUTE, minute);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
//			if(cal.getTimeInMillis() < System.currentTimeMillis()){
//				cal.add(Calendar.MONTH, 1);
//			}
//			return cal;
			return check(cal, Calendar.MONTH, duration);//下个月
		}
	},

	/** 每年 */
	ANNUAL{
		@Override
		public Calendar resolve(int expression, int duration) {
			int minute = expression % 100;
			expression = expression / 100;
			int hour = expression % 100;
			expression = expression / 100;
			int dayofm = expression % 100;
			int month = expression / 100;
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.MONTH, month);
			cal.set(Calendar.DAY_OF_MONTH, dayofm);
			cal.set(Calendar.HOUR_OF_DAY, hour);
			cal.set(Calendar.MINUTE, minute);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			return check(cal, Calendar.YEAR, duration);//下一年
		}
	};

	public abstract Calendar resolve(int expression, int duration);
	
	protected Calendar check(Calendar cal, int field, int duration){
		long lt = cal.getTimeInMillis() + duration;
		if(lt < System.currentTimeMillis()){
			cal.add(field, 1);
		}
		return cal;
	}
}
